import { WebGLCanvas } from "@nirvana/canvas";
import {
  AmbientLight,
  Camera,
  Data,
  DataElement,
  Entity,
  Geometry,
  Mesh,
  PointLight,
  ShaderMaterial
} from "@nirvana/core";
import { Color, Vector3 } from "@nirvana/math";
import { Shader } from "@nirvana/shaders";

async function main() {
  let canvas = document.getElementById("engine-nirvana");
  const webCanvas = new WebGLCanvas(canvas, {
    rate: 1
  });

  const engine = webCanvas.engine;

  const scene = engine.sceneManager.createScene("root");
  const camera = new Camera(engine);
  scene.addCamera(camera);
  camera.transform.setPosition(new Vector3(0, 0, 20));
  const rootEntity = new Entity("root-entity");
  scene.addEntity(rootEntity);

  const ambLight = new AmbientLight("alight");
  ambLight.color = new Color(0.1, 0.1, 0.1, 1);
  const pLight = new PointLight("plight");
  pLight.position = new Vector3(0, 0, 20);
  pLight.color = new Color(1.0, 0.8, 0.8, 1.0);
  scene.addLight(ambLight);
  scene.addLight(pLight);

  webCanvas.onClick = (e) => {
    console.log(e);
    const rect = canvas?.getBoundingClientRect();
    console.log(rect);
  };

  const vs = `
  attribute vec4 POSITION;

  uniform mat4 u_localMat;
  uniform mat4 u_modelMat;
  uniform mat4 u_viewMat;
  uniform mat4 u_projMat;
  uniform mat4 u_MVMat;
  uniform mat4 u_MVPMat;
  uniform mat4 u_normalMat;
  uniform vec3 u_cameraPos;

  void main() {
    gl_Position = POSITION;
    gl_PointSize = 10.0;
  }
  `;
  const fs = `
  void main() {
    gl_FragColor = vec4(1.0,1.0,1.0,1.0);
  }
  `;

  const shader = Shader.create("light-demo", vs, fs);
  const material = new ShaderMaterial("", shader);

  webCanvas._strokeMoveUpdate = (event) => {
    // console.log(e)
    const x = event.clientX;
    const y = event.clientY;

    const nx = (event.clientX - webCanvas.left - webCanvas.width / 2) / (webCanvas.width / 2);
    const ny = (webCanvas.height / 2 - (event.clientY - webCanvas.top)) / (webCanvas.height / 2);

    const gem = new Geometry();
    gem.addData(new Data(new Float32Array([nx, ny, 0]), [new DataElement("POSITION", 3)]));
    const mesh = new Mesh(gem, material);
    mesh.setDrawMode("points");
    rootEntity.add(mesh);
  };
}

main();
